package org.example.server.app.goods.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import org.example.api.goods.category.controller.CategoryControllerFeign;
import org.example.api.goods.category.request.CategorySearchWithLevelPageRequest;
import org.example.api.goods.category.response.CategorySummaryResponse;
import org.example.frw.api.base.request.PageQueryRequest;
import org.example.frw.verify.annotations.Verify;
import org.example.server.app.goods.request.HomeCategoryListRequest;
import org.example.server.app.goods.response.category.CategoryTreeResponse;
import org.example.server.app.goods.service.CategoryService;
import org.example.server.app.goods.verify.HomeCategoryListRequestVerify;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
  private final CategoryControllerFeign categoryFeign;

  public CategoryServiceImpl(CategoryControllerFeign categoryControllerFeign) {
    this.categoryFeign = categoryControllerFeign;
  }

  @Override
  @Verify(verifalClass = HomeCategoryListRequestVerify.class)
  public CategoryTreeResponse searchCategory(HomeCategoryListRequest homeCategoryListRequest) {
    // 先查询第一层的层级
    CategorySummaryResponse categorySummary = categoryFeign.findOne(homeCategoryListRequest.getId());
    if(categorySummary == null){
      return new CategoryTreeResponse();
    }
    // 查询小于等于这个层级+2的分类
    Integer level = categorySummary.getLevel()+1;
    CategorySearchWithLevelPageRequest searchRequest = new CategorySearchWithLevelPageRequest();
    searchRequest.setMinLevel(level);
    searchRequest.setLevel(level + 2);
    searchRequest.setPage(new PageQueryRequest(1,Integer.MAX_VALUE));
    List<CategorySummaryResponse> summaries = categoryFeign.searchCategory( searchRequest);
    if(CollUtil.isEmpty(summaries)){
      return new CategoryTreeResponse();
    }
    // 分类已经就绪，根据分类创建tree
    TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
    treeNodeConfig.setParentIdKey("categoryParentId");
    treeNodeConfig.setIdKey("id");
    treeNodeConfig.setChildrenKey("children");
    treeNodeConfig.setDeep(3);
    List<Tree<Long>> trees = TreeUtil.build(summaries, homeCategoryListRequest.getId(), treeNodeConfig,
            (treeNode, tree) -> {
              tree.setId(treeNode.id());
              tree.setParentId(treeNode.getCategoryParentId());
              tree.setName(treeNode.getCategoryName());
              tree.putExtra("parent_id",treeNode.getCategoryParentId());
              tree.putExtra("name",treeNode.getCategoryName());
              tree.putExtra("image",treeNode.getCategoryImageUrl());
            });
    // 树创建完毕之后，构造返回
    CategoryTreeResponse categoryTreeResponse = new CategoryTreeResponse();
    categoryTreeResponse.setChildren(trees);
    return categoryTreeResponse;
  }
}
